package com.example.mainstream.ui.user;

import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.View;

import com.bumptech.glide.Glide;
import com.example.shopapp.App;
import com.example.shopapp.R;
import com.example.shopapp.bean.Goods;
import com.example.shopapp.bean.Merchant;
import com.example.shopapp.bean.Order;
import com.example.shopapp.bean.OrderBean;
import com.example.shopapp.bean.Select;
import com.example.shopapp.bean.ShopAddress;
import com.example.shopapp.bean.Shoucang;
import com.example.shopapp.bean.Yugou;
import com.example.shopapp.dao.MerchantDao;
import com.example.shopapp.dao.SelectDao;
import com.example.shopapp.dao.ShoucangDao;
import com.example.shopapp.database.GreenDaoManager;
import com.example.shopapp.database.OrderBeanDBUtils;
import com.example.shopapp.database.ShopAddressDBUtils;
import com.example.shopapp.databinding.ActivityGoodsDetailBinding;
import com.example.shopapp.ui.dialog.OnPayLinstener;
import com.example.shopapp.ui.dialog.PayTypesDialog;
import com.example.shopapp.ui.merchant.ShopListActivity;
import com.example.shopapp.utils.Utils;
import com.hb.dialog.myDialog.MyPayInputDialog;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.interfaces.OnDialogButtonClickListener;

import org.greenrobot.eventbus.EventBus;
import org.xutils.ex.DbException;

import java.util.List;

import cn.project.base.baseui.BaseNormalActivity;

public class GoodsDetailActivity extends BaseNormalActivity<ActivityGoodsDetailBinding> implements OnPayLinstener {
    Goods goods =null;
    MerchantDao merchantDao;
    SelectDao selectDao;
    ShoucangDao shoucangDao;
    String address_id = "";
    Merchant merchant;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_goods_detail;
    }

    @Override
    protected void initView() {
        goods = (Goods) getIntent().getSerializableExtra("goods");
        selectDao = GreenDaoManager.getmInstance().getDaoSession().getSelectDao();
        shoucangDao = GreenDaoManager.getmInstance().getDaoSession().getShoucangDao();
        select();
        mBinding.toolbar.rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        mBinding.toolbar.tvTitle.setText("商品详情");
        merchantDao = GreenDaoManager.getmInstance().getDaoSession().getMerchantDao();
        mBinding.toolbar.tvRight.setText("收藏");
        mBinding.toolbar.tvRight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shoucang();
            }
        });
    }
    String title ;;
    String content ;

    @Override
    protected void initData() {

        Glide.with(this).load(goods.getUrl()).into(mBinding.image);
        mBinding.tvGoodsTitle.setText(goods.getTitle()+"");
        mBinding.tvDes.setText(goods.getContent()+"");
        mBinding.tvType.setText(goods.getGoods_type()+"");
        mBinding.tvAddress.setText("产地："+goods.getAddress());
        mBinding.tvDetailAddress.setText("详细地址："+goods.getDetail_address());
        mBinding.tvPrice.setText("¥："+goods.getPrice());
        mBinding.btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addCar();
            }
        });

        mBinding.btnYugou.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add();
            }
        });
        mBinding.tvPhone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_DIAL);
                intent.setData(Uri.parse("tel:"+merchant.getPhone()));
                startActivity(intent);
            }
        });
        mBinding.tvMerchant.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent =new Intent(GoodsDetailActivity.this, ShopListActivity.class);
                intent.putExtra("merchant",merchant);
                startActivity(intent);
            }
        });

        List<Merchant> merchantList = merchantDao.loadAll();
        for (int i = 0; i < merchantList.size(); i++) {
            if (goods.getUserid() == merchantList.get(i).getId()){
                merchant = merchantList.get(i);
                if (!TextUtils.isEmpty(merchantList.get(i).getPhone())){
                    mBinding.tvPhone.setText("客服电话："+merchantList.get(i).getPhone());
                }
                if (!TextUtils.isEmpty(merchantList.get(i).getUsername())){
                    mBinding.tvMerchant.setText("店铺名称："+merchantList.get(i).getUsername());
                }
                return;
            }
        }
    }

    private void shoucang(){
        List<Shoucang> selectList = shoucangDao.loadAll();
        if (selectList ==null || selectList.size() ==0){
            Shoucang select = new Shoucang();
            select.setId(System.currentTimeMillis());
            select.setGood_id(goods.getId());
            select.setUser_id(App.getInstance().user.getUser_id());
            shoucangDao.insert(select);
            MessageDialog.build()
                    .setTitle("提示")
                    .setMessage("收藏成功")
                    .setOkButton("确定")
                    .show();
            return;
        }
        boolean has = false;
        for (int i = 0; i < selectList.size(); i++) {
            if (App.getInstance().user.getUser_id().equals(selectList.get(i).getUser_id())
                    && goods.getId() == selectList.get(i).getGood_id()){
                has = true;
            }
        }

        if (!has){
            Shoucang select = new Shoucang();
            select.setId(System.currentTimeMillis());
            select.setGood_id(goods.getId());
            select.setUser_id(App.getInstance().user.getUser_id());
            shoucangDao.insert(select);
            MessageDialog.build()
                    .setTitle("提示")
                    .setMessage("收藏成功")
                    .setOkButton("确定")
                    .show();
            return;
        }
        MessageDialog.build()
                .setTitle("提示")
                .setMessage("已经收藏，无需重复收藏")
                .setOkButton("确定")
                .show();
    }

    private void select(){
        List<Select> selectList = selectDao.loadAll();
        if (selectList ==null || selectList.size() ==0){
            Select select = new Select();
            select.setId(System.currentTimeMillis());
            select.setGood_id(goods.getId());
            select.setUser_id(App.getInstance().user.getUser_id());
            selectDao.insert(select);
            return;
        }
        boolean has = false;
        for (int i = 0; i < selectList.size(); i++) {
            if (App.getInstance().user.getUser_id().equals(selectList.get(i).getUser_id())
            && goods.getId() == selectList.get(i).getGood_id()){
                has = true;
            }
        }

        if (!has){
            Select select = new Select();
            select.setId(System.currentTimeMillis());
            select.setGood_id(goods.getId());
            select.setUser_id(App.getInstance().user.getUser_id());
            selectDao.insert(select);
        }
    }

    private void add(){
        List<ShopAddress> shopAddressList = ShopAddressDBUtils.getInstance(getApplicationContext()).getListShopAddress(App.getInstance().user.getUser_id());
        if(shopAddressList.size() == 0){//判断是否有收获地址
            addShopAddress();
        }else {
            boolean isDefault = false;
            for (int i = 0; i < shopAddressList.size(); i++) {
                if("0".equals(shopAddressList.get(i).getDefaultcity())){
                    address_id = shopAddressList.get(i).getAddress_id();
                    isDefault = true;
                }
            }
            if (isDefault){
                choosePayWays();
            }else {
                addShopAddress();
            }

        }
    }

    private void choosePayWays() {
        pay("微信支付");
    }

    private void addShopAddress() {
        MessageDialog.build()
                .setTitle("提示")
                .setMessage("还未设置收货地址，请先添加收货地址")
                .setOkButton("确定", new OnDialogButtonClickListener<MessageDialog>() {
                    @Override
                    public boolean onClick(MessageDialog dialog, View v) {
                        startActivity(new Intent(GoodsDetailActivity.this, ShopAddressListActivity.class));
                        return false;
                    }
                })
                .setCancelButton("取消")
                .show();
    }

    private void addCar(){
        boolean isChoose = false;
        if(Utils.orderList.size() > 0){
            title = mBinding.tvGoodsTitle.getText().toString();
            content = mBinding.tvDes.getText().toString();
            for (int i = 0; i <Utils.orderList.size(); i++) {
                if(title.equals(Utils.orderList.get(i).getTitle()) && content.equals(Utils.orderList.get(i).getContent())){
                    isChoose = true;
                }
            }
        }

        if (isChoose){
            showToast("已经加入购物车");
            return;
        }
        Order order = new Order();
        order.setContent(goods.getContent());
        order.setGoods_type(goods.getGoods_type());
        order.setTitle(goods.getTitle());
        order.setPrice(goods.getPrice());
        order.setUrl(goods.getUrl());
        order.setTime(goods.getTime());
        order.setAddress(goods.getAddress());
        order.setMerchatId(goods.getUserid());
        order.setDetail_address(goods.getDetail_address());
        order.setUserid(App.getInstance().user.getUser_id());
        order.setIsselect(true);
        Utils.orderList.add(order);
        order.setCount(1);
        showToast("加入购物车");
        EventBus.getDefault().postSticky("购物车");//刷新购物车
    }

    @Override
    public void onPayClick(int type) {
        switch (type){
            case 1:
                pay("支付宝支付");
                break;
            case 2:
                pay("微信支付");
                break;
            default:
                break;
        }
    }

    private void pay(String msg){
        final MyPayInputDialog myPayInputDialog = new MyPayInputDialog(GoodsDetailActivity.this).Builder();
        myPayInputDialog.setResultListener(new MyPayInputDialog.ResultListener() {
            @Override
            public void onResult(String result) {
                OrderBean orderBean = new OrderBean();
                orderBean.setUrl(goods.getUrl());
                orderBean.setGoods_type(goods.getGoods_type());
                orderBean.setState("0");
                orderBean.setPrice(goods.getPrice());
                orderBean.setTitle(goods.getTitle());
                orderBean.setCount("1");
                orderBean.setId(System.currentTimeMillis());
                orderBean.setAddress_id(address_id);
                orderBean.setDetail_address(goods.getDetail_address());
                orderBean.setAddress(goods.getAddress());
                orderBean.setMerchatid(goods.getUserid());
                orderBean.setUser_id(App.getInstance().user.getUser_id());
                orderBean.setContent(goods.getContent());
                OrderBeanDBUtils.getInstance(getApplicationContext()).insert(orderBean);
                showToast("支付成功");
                address_id = "";
                myPayInputDialog.dismiss();
            }
        }).setTitle(msg);
        myPayInputDialog.show();


    }
}
